package org.example.virtualsensors.entity.model;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.Getter;
import org.example.virtualsensors.entity.EmsItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.nio.charset.StandardCharsets;
import java.util.*;

@Getter
public class Sensor {
    //todo 传感器添加重复 这个需要解决
    public EmsItem emsItem=new EmsItem();
    public Thread thread_heartbeat;
    public Thread thread_realtimeData;
    public Sensor(){
        //添加两个检测量
        EmsQuantity  temperature= new EmsQuantity("temperature","A001","property1");
        temperature.setId("U001");
        temperature.setAlarmColor("red");
        temperature.setAlarmValue(50f);
        temperature.setAlarmTimes(0);
        temperature.setData(20f);
        temperature.setUpperLimit(100f);
        temperature.setLowerLimit(0f);
        temperature.setQuantityName("temperature");
        temperature.setItemgroupKey("2");
        temperature.setClopenStatus(1);
        temperature.setItemgroupId("sss");
        temperature.setStatus(1);
        temperature.setItemgroupSn("10000002");
        temperature.setUnitName("te");
        temperature.setStatus(1);
        temperature.setType(1);
        temperature.setItemKey(emsItem.getItemKey());
        temperature.setQuantityKey(1);
        temperature.setId(emsItem.getId());
        temperature.setItemId(emsItem.getId());
        emsItem.getQuantities().add(temperature);


        // todo 找出查询传感器不一样的问题
    }


    public static void setSensorRegistrationUrl(String sensorRegistrationUrl) {
        Sensor.sensorRegistrationUrl = sensorRegistrationUrl;
    }

    public static void setSensorHeartbeatUrl(String sensorHeartbeatUrl) {
        Sensor.sensorHeartbeatUrl = sensorHeartbeatUrl;
    }

    public static void setSensorDataReportUrl(String sensorDataReportUrl) {
        Sensor.sensorDataReportUrl = sensorDataReportUrl;
    }

    public static void setSensorHistoryDataReportUrl(String sensorHistoryDataReportUrl) {
        Sensor.sensorHistoryDataReportUrl = sensorHistoryDataReportUrl;
    }


    //    传感器注册请求地址
    @Getter
    public static String sensorRegistrationUrl = "http://localhost:58080/gateway/item/register";
    //    心跳接口
    @Getter
    public static String sensorHeartbeatUrl = "http://localhost:58080/gateway/item/heartbeat";
    //    上报实时数据接口
    @Getter
    public static String sensorDataReportUrl = "http://localhost:58080/gateway/realtime/upload";
    //    上报历史数据
    @Getter
    public static String sensorHistoryDataReportUrl = "http://localhost:58080/gateway/history/upload";


    public void registerSensor(String sensorRegistrationUrl) {
        String jsonStr = JSONUtil.toJsonStr(emsItem);

        // 设置编码为 GB2312
        HttpUtil.createPost(sensorRegistrationUrl)
                .header("Content-Type", "application/json; charset=GB2312")
                .body(jsonStr, String.valueOf(StandardCharsets.UTF_8)) // 可以选择转换为 GB2312 编码
                .execute();

        reportRealtimeData();
    }
    // 注册传感器
    public void registerSensor() {
        String jsonStr = JSONUtil.toJsonStr(emsItem);

        // 设置编码为 GB2312
        HttpUtil.createPost(sensorRegistrationUrl)
                .header("Content-Type", "application/json; charset=GB2312")
                .body(jsonStr, String.valueOf(StandardCharsets.UTF_8)) // 可以选择转换为 GB2312 编码
                .execute();

        reportRealtimeData();
    }

//    上报实时数据

    @Autowired
    private StringRedisTemplate redisTemplate;
    public void reportRealtimeData(String sensorDataReportUrl,String jsonData) {
        if(thread_realtimeData!=null&&thread_realtimeData.isAlive()){
            System.out.println("正在上报实时数据");
            return;
        };
        if(thread_realtimeData==null)thread_realtimeData=new Thread(()->{
            while (true){
                try {
                    System.out.println("正在上报实时数据");
                    redisTemplate.opsForValue().set(this.getEmsItem().getItemgroupSn()+this.getEmsItem().getItemgroupKey()+"REALTIMEDATA_CACHE",jsonData);
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread_realtimeData.start();
    }
    public void reportRealtimeData() {
        if(thread_realtimeData!=null&&thread_realtimeData.isAlive()){
            System.out.println("正在上报实时数据");
            return;
        }

        Map<String, Object> data = new HashMap<>();
        data.put("itemgroupKey", "2");
        data.put("itemgroupModel", "EMS3000");
        data.put("itemgroupSn", "10000002");
        data.put("modrtu", "[{\"itemKey\":\"1610\",\"total\":\"3\",\"devtype\":\"TYPE_A\",\"btnNum\":\"2\"},{\"mdrtu0\":\"value1\"},{\"mdrtu1\":\"value2\"},{\"mdrtu2\":\"value3\"}]");

        // 将数据转换为 JSON 格式的字符串
        String jsonData = JSONUtil.toJsonStr(data);

        // 调用 HttpUtil.post 方法上报数据
        try {
            String response = HttpUtil.post(sensorDataReportUrl, jsonData);
            System.out.println("上报结果: " + response);
        } catch (Exception e) {
            System.out.println("上报失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
//    上传历史数据
    public void reportHistoryData() {
    }
}